<template>
  <div class="app-container fileManagement">
    <div ref="dragBox" class="dragBox">
      <!--文件树形数据-->
      <div ref="left" class="left">
        <div class="head-container">
          <el-input
            v-model="serverFilename"
            placeholder="请输入文件名"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            ref="tree"
            :data="fileOptions"
            :props="defaultProps"
            node-key="id"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            :default-expand-all="true"
            :highlight-current="true"
            :current-node-key="currentNodeKey"
            @node-click="handleNodeClick"
          >
            <span slot-scope="{ node, data }" class="custom-tree-node" @contextmenu.prevent="openMenu($event, data)">
              <span class="el-tree-node__label">
                <svg-icon v-if="data.isdir === '1' && node.expanded && !node.isLeaf" icon-class="folderOpen" />
                <svg-icon v-else-if="(data.isdir === '1' && node.isLeaf) || (data.isdir === '1' && !node.expanded)" icon-class="folderClose" />
                <svg-icon v-else-if="data.isdir === '0' && 'jpg_png_jpeg'.indexOf(data.category) !== -1" icon-class="jpg_png" />
                <svg-icon v-else-if="data.isdir === '0' && 'mov_mp4_avi'.indexOf(data.category) !== -1" icon-class="mov_mp4_avi" />
                <svg-icon v-else-if="data.isdir === '0' && 'mp3_wav'.indexOf(data.category) !== -1" icon-class="mp3_wav" />
                <svg-icon v-else-if="data.isdir === '0' && 'pdf'.indexOf(data.category) !== -1" icon-class="pdf1" />
                <svg-icon v-else-if="data.isdir === '0' && 'txt'.indexOf(data.category) !== -1" icon-class="txt" />
                <svg-icon v-else-if="data.isdir === '0' && 'docx_doc'.indexOf(data.category) !== -1" icon-class="docx_doc" />
                <svg-icon v-else-if="data.isdir === '0' && 'xlsx_xls'.indexOf(data.category) !== -1" icon-class="xlxs_xls" />
                <svg-icon v-else-if="data.isdir === '0' && 'ppt_pptx'.indexOf(data.category) !== -1" icon-class="ppt_pptx" />
                <svg-icon v-else-if="data.isdir === '0' && 'zip_rar_gz_bz2'.indexOf(data.category) !== -1" icon-class="archive" />
                <svg-icon v-else icon-class="files" />
                {{ node.label }}
              </span>
            </span>
          </el-tree>
        </div>
      </div>

      <div ref="resize" class="resize" />

      <!--文件列表数据-->
      <div ref="right" class="right">
        <el-form v-show="showSearch" ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
          <el-form-item label="文件名" prop="serverFilename">
            <el-input
              v-model="queryParams.serverFilename"
              placeholder="请输入文件名"
              clearable
              size="small"
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <div class="mb8 tableRibbon">
          <div v-if="!leftClickItem">
            <el-button
              v-hasPermi="['documentation:management:add']"
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd()"
            >新增</el-button>
          </div>

          <div class="pathArea">
            <div v-for="(item, index) in pathUrlList" :key="index" class="pathUrl">
              <svg-icon icon-class="folderClose" />
              <span @click="pathUrlJump(item)">{{ item.path }}</span>
              <i v-if="index !== pathUrlList.length - 1" class="el-icon-arrow-right" />
            </div>
          </div>

          <right-toolbar :show-search.sync="showSearch" :columns="columns" @queryTable="getList" />
        </div>

        <el-table
          v-loading="loading"
          :data="userList"
          highlight-current-row
          @row-dblclick="handleTableClick"
          @row-contextmenu="(row, column, $event) => openMenu($event, row)"
        >
          <el-table-column type="index" width="50" align="center" fixed="left" />

          <el-table-column v-if="columns[0].visible" key="serverFilename" label="文件名" align="left" header-align="center" show-overflow-tooltip prop="serverFilename" min-width="240">
            <template slot-scope="scope">
              <svg-icon v-if="scope.row.isdir === '1'" icon-class="folderClose" font-size="28px" />
              <svg-icon v-else-if="scope.row.isdir === '0' && 'jpg_png_jpeg'.indexOf(scope.row.category) !== -1" icon-class="jpg_png" font-size="28px" />
              <svg-icon v-else-if="scope.row.isdir === '0' && 'mov_mp4_avi'.indexOf(scope.row.category) !== -1" icon-class="mov_mp4_avi" font-size="28px" />
              <svg-icon v-else-if="scope.row.isdir === '0' && 'mp3_wav'.indexOf(scope.row.category) !== -1" icon-class="mp3_wav" font-size="28px" />
              <svg-icon v-else-if="scope.row.isdir === '0' && 'pdf'.indexOf(scope.row.category) !== -1" icon-class="pdf1" font-size="28px" />
              <svg-icon v-else-if="scope.row.isdir === '0' && 'txt'.indexOf(scope.row.category) !== -1" icon-class="txt" font-size="28px" />
              <svg-icon v-else-if="scope.row.isdir === '0' && 'docx_doc'.indexOf(scope.row.category) !== -1" icon-class="docx_doc" font-size="28px" />
              <svg-icon v-else-if="scope.row.isdir === '0' && 'xlsx_xls'.indexOf(scope.row.category) !== -1" icon-class="xlxs_xls" font-size="28px" />
              <svg-icon v-else-if="scope.row.isdir === '0' && 'ppt_pptx'.indexOf(scope.row.category) !== -1" icon-class="ppt_pptx" font-size="28px" />
              <svg-icon v-else-if="scope.row.isdir === '0' && 'zip_rar_gz_bz2'.indexOf(scope.row.category) !== -1" icon-class="archive" font-size="28px" />
              <svg-icon v-else icon-class="files" font-size="28px" />
              <span style="margin-left: 5px">{{ scope.row.serverFilename }}</span>
            </template>
          </el-table-column>

          <el-table-column v-if="columns[2].visible" label="类型" align="center" prop="isdir" min-width="100">
            <template slot-scope="scope">
              <span>{{ scope.row.isdir === '1' ? '文件夹' : '文件' }}</span>
            </template>
          </el-table-column>

          <el-table-column v-if="columns[3].visible" key="category" label="文件类型" align="center" prop="category" min-width="100">
            <template slot-scope="scope">
              <span>{{ scope.row.isdir === '1' ? '#' : scope.row.category }}</span>
            </template>
          </el-table-column>

          <el-table-column v-if="columns[5].visible" key="fileSize" label="文件大小" align="center" prop="fileSize" min-width="100" />

          <el-table-column v-if="columns[4].visible" key="uploader" label="文件上传人" align="center" prop="uploader" min-width="100">
            <template slot-scope="scope">
              <span>{{ scope.row.isdir === '1' ? '#' : scope.row.uploader }}</span>
            </template>
          </el-table-column>

          <el-table-column v-if="columns[1].visible" label="上传日期" align="center" prop="uptime" min-width="160">
            <template slot-scope="scope">
              <span>{{ scope.row.uptime }}</span>
            </template>
          </el-table-column>

          <el-table-column
            label="操作"
            align="center"
            width="160"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                v-hasPermi="['documentation:management:edit']"
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
              >修改</el-button>
              <el-button
                v-hasPermi="['documentation:management:remove']"
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
              >删除</el-button>

              <el-dropdown
                size="mini"
                @command="(command) => handleCommand(command, scope.row)"
              >
                <span class="el-dropdown-link">
                  <i class="el-icon-d-arrow-right el-icon--right" />更多
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item
                    v-if="scope.row.isdir === '1'"
                    v-hasPermi="['documentation:management:add']"
                    command="handleAdd"
                    icon="el-icon-plus"
                  >新增</el-dropdown-item>

                  <el-dropdown-item
                    v-if="scope.row.isdir === '0'"
                    v-hasPermi="['documentation:management:preview']"
                    command="handlePreview"
                    icon="el-icon-view"
                  >预览</el-dropdown-item>

                  <el-dropdown-item
                    v-if="scope.row.isdir === '0'"
                    v-hasPermi="['documentation:management:download']"
                    command="handleDownload"
                    icon="el-icon-download"
                  >下载</el-dropdown-item>

                  <el-dropdown-item
                    v-hasPermi="['documentation:management:authorize']"
                    command="handleAuthorize"
                    icon="el-icon-s-check"
                  >授权</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </div>
    </div>

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row v-if="!rightClickItem || rightClickItem.isdir === '1'">
          <el-col :span="12">
            <el-form-item label="类型" prop="isdir">
              <el-radio-group v-model="form.isdir">
                <el-radio label="0" :disabled="title === '修改文件' || !leftClickItem">文件</el-radio>
                <el-radio label="1" :disabled="title === '修改文件'">文件夹</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-if="form.isdir === '1' || title === '修改文件' ">
          <el-col :span="24">
            <el-form-item label="文件名" prop="serverFilename">
              <el-input v-model="form.serverFilename" placeholder="请输入文件名" maxlength="30" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-if="form.isdir === '0' && title !== '修改文件'">
          <el-col :span="24">
            <el-form-item label="文件上传" prop="url">
              <FileUpload
                :file-size="100"
                :limit="5"
                :value="fileList"
                upload-url="/oa/file/uploadSingleFile"
                @input="uploadFileChange"
              />
              <BigFileUpload @bigFileFinished="bigFileChange" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 授权对话框 -->
    <el-dialog title="文件授权" :visible.sync="authorizeOpen" width="600px" append-to-body>
      <el-form ref="authorizeForm" :model="authorizeForm" :rules="authorizeRules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="授权部门" prop="deptIds">
              <treeselect
                v-model="authorizeForm.deptIds"
                :options="deptOptions"
                :show-count="true"
                :multiple="true"
                placeholder="请选择授权部门"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAuthorizeForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 右键菜单 -->
    <ul v-if="rightMenuVisible" :style="{left: left + 'px', top: top + 'px'}" class="contextmenu">
      <li v-if="rightClickItem.isdir === '1'" v-hasPermi="['documentation:management:add']" @click="handleAdd()"><i class="el-icon-plus" /> 新增</li>
      <li v-if="rightClickItem.isdir === '0'" v-hasPermi="['documentation:management:preview']" @click="handlePreview()"><i class="el-icon-view" /> 预览</li>
      <li v-if="rightClickItem.isdir === '0'" v-hasPermi="['documentation:management:download']" @click="handleDownload()"><i class="el-icon-download" /> 下载</li>
      <li v-hasPermi="['documentation:management:edit']" @click="handleUpdate()"><i class="el-icon-edit" /> 修改</li>
      <li v-hasPermi="['documentation:management:remove']" @click="handleDelete()"><i class="el-icon-delete" /> 删除</li>
      <li v-hasPermi="['documentation:management:authorize']" @click="handleAuthorize()"><i class="el-icon-s-check" /> 授权</li>
    </ul>
  </div>
</template>

<script>
import { listFile, treeFile, getFileDetail, addFile, updateFile, delFile, addByType, addFileLimit, getLimitDetail, uploadFile } from '@/api/documentation/management'
import { treeselect } from '@/api/system/dept'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

export default {
  name: 'File',

  components: { Treeselect },

  data() {
    var validateAttach = (rule, value, callback) => {
      if (this.fileList.length <= 0 && this.bigFileList.length <= 0) {
        callback(new Error('请上传文档'))
      } else {
        callback()
      }
    }

    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: '',
      // 文件树选项
      fileOptions: undefined,
      // 部门树选项
      deptOptions: undefined,
      // 增加修改弹出层
      open: false,
      // 授权弹出层
      authorizeOpen: false,
      // 文件名
      serverFilename: undefined,
      // 新增修改表单参数
      form: {},
      // 上传文件列表
      fileList: [],
      fileMap: null,
      bigFileList: [],
      // 授权表单参数
      authorizeForm: {},
      defaultProps: {
        children: 'children',
        label: 'serverFilename'
      },
      // 默认选中节点
      currentNodeKey: '',
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        serverFilename: undefined
      },
      // 列信息
      columns: [
        { key: 0, label: `文件名`, visible: true },
        { key: 1, label: `上传日期`, visible: true },
        { key: 2, label: `类型`, visible: true },
        { key: 3, label: `文件类型`, visible: true },
        { key: 4, label: `文件上传人`, visible: true },
        { key: 5, label: `文件大小`, visible: true }
      ],
      // 表单校验
      rules: {
        serverFilename: [
          { required: true, message: '文件名不能为空', trigger: 'blur' },
          { min: 2, max: 20, message: '文件名长度必须介于 2 和 20 之间', trigger: 'blur' }
        ],
        isdir: [
          { required: true, message: '请选择文件类型', trigger: 'change' }
        ],
        url: [
          { required: true, validator: validateAttach, trigger: 'blur' }
        ]
      },
      authorizeRules: {
        deptIds: [
          { required: true, message: '请选择授权部门', trigger: 'change' }
        ]
      },
      leftClickItem: null,
      rightClickItem: null,
      rightMenuVisible: false,
      top: 0,
      left: 0
    }
  },

  computed: {
    userName() {
      return this.$store.getters.name
    },

    pathUrlList() {
      if (this.leftClickItem) {
        const pathList = this.leftClickItem.parentPath.split('/').filter(val => {
          return !!val
        })

        const idList = this.leftClickItem.parentIdPath.split('/').filter(val => {
          return !!val
        }).concat([this.leftClickItem.id])

        const list = pathList.map((val, index) => {
          return {
            path: val,
            id: idList[index]
          }
        })
        return list
      } else {
        return []
      }
    }
  },

  watch: {
    // 根据名称筛选部门树
    serverFilename(val) {
      this.$refs.tree.filter(val)
    },

    rightMenuVisible(value) {
      if (value) {
        document.body.addEventListener('click', this.closeMenu)
      } else {
        document.body.removeEventListener('click', this.closeMenu)
      }
    }
  },

  created() {
    this.getTreeselect()
    this.getDeptTree()
  },

  mounted() {
    this.dragControllerDiv()
  },

  methods: {
    /** 查询用户列表 */
    getList() {
      this.loading = true
      const params = {
        ...this.queryParams,
        fid: this.leftClickItem ? this.leftClickItem.id : ''
      }
      listFile(params).then(response => {
        this.userList = response.rows
        this.total = response.total
        this.loading = false
      })
    },

    /** 查询文件下拉树结构 */
    getTreeselect() {
      treeFile().then(response => {
        console.log('treeData', response)
        this.fileOptions = response.data
        this.leftClickItem = response.data.length > 0 ? response.data[0] : null
        this.$nextTick(() => {
          this.currentNodeKey = response.data.length > 0 ? response.data[0].id : ''
          this.$refs['tree'].setCurrentKey(this.currentNodeKey)
        })
        this.getList()
      })
    },

    /** 查询部门下拉树结构 */
    getDeptTree() {
      treeselect().then(response => {
        this.deptOptions = response.data
      })
    },

    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.serverFilename.indexOf(value) !== -1
    },

    // 节点单击事件
    handleNodeClick(data, node) {
      console.log('节点单击事件', data)
      this.closeMenu()
      if (data.isdir === '0') return
      this.leftClickItem = data
      this.queryParams.fid = data.id
      this.handleQuery()
    },

    // 路径节点跳转
    pathUrlJump(item) {
      this.currentNodeKey = item.id
      this.$refs['tree'].setCurrentKey(this.currentNodeKey)
      this.$nextTick(() => {
        document.querySelector('.is-current').firstChild.click()
      })
    },

    // 表格双击事件
    handleTableClick(data) {
      if (data.isdir === '0') return
      this.leftClickItem = data
      this.queryParams.fid = data.id
      this.handleQuery()

      this.currentNodeKey = data.id
      this.$refs['tree'].setCurrentKey(this.currentNodeKey)
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.authorizeOpen = false
      this.reset()
    },

    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        fid: undefined,
        serverFilename: undefined,
        url: undefined,
        category: undefined
      }
      this.fileList = []
      this.fileMap = []
      this.bigFileList = []
      this.authorizeForm = {
        fileId: undefined,
        deptIds: undefined
      }
      this.resetForm('form')
      this.resetForm('authorizeForm')
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },

    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case 'handleAdd':
          this.handleAdd(row)
          break
        case 'handlePreview':
          this.handlePreview(row)
          break
        case 'handleDownload':
          this.handleDownload(row)
          break
        case 'handleAuthorize':
          this.handleAuthorize(row)
          break
        default:
          break
      }
    },

    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset()
      this.open = true
      this.title = '添加文件'
      this.rightClickItem = row || this.rightClickItem
      console.log('选择新增的对象', this.rightClickItem)
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const val = row || this.rightClickItem
      getFileDetail(val.id).then(response => {
        this.form = response.data
        // this.fileList = [
        //   {
        //     name: response.data.serverFilename,
        //     url: response.data.url
        //   }
        // ]
        this.open = true
        this.title = '修改文件'
      })
    },

    /** 授权 */
    handleAuthorize(row) {
      this.reset()
      const val = row || this.rightClickItem
      getLimitDetail(val.id).then(response => {
        console.log('授权', response)
        this.authorizeForm = {
          ...this.authorizeForm,
          fileId: val.id,
          deptIds: response.data.deptIds ? response.data.deptIds.split(',').map(Number) : []
        }
        this.authorizeOpen = true
      })
    },

    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id !== undefined) {
            updateFile(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getTreeselect()
            })
          } else {
            if (this.form.isdir === '1') {
              // 新增文件夹
              const params = {
                ...this.form,
                uploader: this.userName,
                fid: this.rightClickItem ? this.rightClickItem.id : '0',
                parentPath: this.rightClickItem ? this.rightClickItem.parentPath + '/' + this.form.serverFilename : '/' + this.form.serverFilename,
                parentIdPath: this.rightClickItem ? this.rightClickItem.parentIdPath + '/' + this.rightClickItem.id : ''
              }
              addFile(params).then(response => {
                this.$modal.msgSuccess('新增成功')
                this.open = false
                this.getTreeselect()
              })
            } else {
              // 新增文件
              if (this.fileList && this.fileList.length > 0) {
                const fileFormData = new FormData()
                for (const val of this.fileMap.values()) {
                  console.log('valval', val)
                  fileFormData.append('files', val)
                }
                uploadFile(fileFormData).then(res => {
                  console.log('上传结果', res)
                  const fileList = res.fileName.map((val, index) => {
                    return {
                      url: val.fileUrl,
                      serverFilename: val.fileName,
                      fileSize: (val.fileSize / 1024 / 1024).toFixed(2) + 'M',
                      category: /\.([0-9A-z]+)$/.exec(val.fileName)[1]
                    }
                  }).concat(this.bigFileList)

                  const params = {
                    ...this.form,
                    fileChild: fileList,
                    uploader: this.userName,
                    fid: this.rightClickItem ? this.rightClickItem.id : '0',
                    parentPath: this.rightClickItem ? this.rightClickItem.parentPath + '/' + this.form.serverFilename : '/' + this.form.serverFilename,
                    parentIdPath: this.rightClickItem ? this.rightClickItem.parentIdPath + '/' + this.rightClickItem.id : ''
                  }
                  addFile(params).then(response => {
                    this.$modal.msgSuccess('新增成功')
                    this.open = false
                    this.getTreeselect()
                  })
                })
              } else {
                const params = {
                  ...this.form,
                  fileChild: this.bigFileList,
                  uploader: this.userName,
                  fid: this.rightClickItem ? this.rightClickItem.id : '0',
                  parentPath: this.rightClickItem ? this.rightClickItem.parentPath + '/' + this.form.serverFilename : '/' + this.form.serverFilename,
                  parentIdPath: this.rightClickItem ? this.rightClickItem.parentIdPath + '/' + this.rightClickItem.id : ''
                }
                addFile(params).then(response => {
                  this.$modal.msgSuccess('新增成功')
                  this.open = false
                  this.getTreeselect()
                })
              }
            }
          }
        }
      })
    },

    // 授权表单提交
    submitAuthorizeForm() {
      this.$refs['authorizeForm'].validate(valid => {
        if (valid) {
          console.log('this.authorizeForm', this.authorizeForm)
          addFileLimit(this.authorizeForm).then(response => {
            this.$modal.msgSuccess('授权成功')
            this.authorizeOpen = false
            this.getTreeselect()
          })
        }
      })
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const val = row || this.rightClickItem
      const prompt = val.isdir === '0' ? '是否确认删除名称为"' + val.serverFilename + '"的文件？' : '是否确认删除名称为 "' + val.serverFilename + '" 的文件夹及其包含的所有文件/文件夹？'
      this.$modal.confirm(prompt).then(function() {
        return delFile(val.id)
      }).then(() => {
        this.getTreeselect()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },

    // 文件预览
    handlePreview(row) {
      const val = row || this.rightClickItem
      window.open(this.baseUrl + val.url)
      this.addByType({ fileId: val.id, operate: '2' })
    },

    // 文件下载
    handleDownload(row) {
      const val = row || this.rightClickItem
      const a = document.createElement('a')
      const url = this.baseUrl + val.url // 完整的url则直接使用
      // 这里是将url转成blob地址，
      fetch(url).then(res => res.blob()).then(blob => { // 将链接地址字符内容转变成blob地址
        a.href = URL.createObjectURL(blob)
        // console.log(a.href)
        a.download = val.serverFilename // 下载文件的名字
        // a.download = url.split('/')[url.split('/').length -1] //  // 下载文件的名字
        document.body.appendChild(a)
        a.click()
      })
      this.addByType({ fileId: val.id, operate: '3' })

      // const a = document.createElement('a')
      // a.href = this.baseUrl + val.url
      // a.click()

      // window.location.href = this.baseUrl + val.url

      // window.open(this.baseUrl + val.url)
    },

    // 文件下载、预览统计
    addByType(val) {
      addByType(val).then(res => {
        console.log('文件下载、预览统计', res)
      })
    },

    // 上传文件增减
    uploadFileChange(list, map) {
      console.log('上传的文件list', list)
      console.log('上传的文件map', map)
      this.fileList = list
      this.fileMap = map
      // this.form.url = list.length > 0 ? list[0].url : undefined
      // this.form.serverFilename = list.length > 0 ? list[0].name : undefined
      // this.form.fileSize = list.length > 0 ? (list[0].fileSize / 1024 / 1024).toFixed(2) + 'M' : undefined
      // this.form.category = list.length > 0 ? list[0].name.slice(list[0].name.lastIndexOf('.') + 1, list[0].name.length) : undefined
      this.$refs.form.validateField('url')
    },

    // 大文件新增
    bigFileChange(file) {
      console.log('bigFileChange', file)
      this.bigFileList = [file]
      this.$refs.form.validateField('url')
    },

    // 打开右键菜单
    openMenu(event, item) {
      // 阻止右键默认行为
      event.preventDefault()
      this.rightClickItem = item
      const x = event.clientX
      const y = event.clientY
      this.top = y
      this.left = x
      this.rightMenuVisible = true
    },

    // 关闭右键菜单
    closeMenu() {
      this.rightMenuVisible = false
    },

    // 鼠标拖动方法
    dragControllerDiv: function() {
      var resize = document.getElementsByClassName('resize')
      var left = document.getElementsByClassName('left')
      var right = document.getElementsByClassName('right')
      var box = document.getElementsByClassName('dragBox')
      // console.log('boxbox', box)
      for (let i = 0; i < resize.length; i++) {
        // 鼠标按下事件
        resize[i].onmousedown = function(e) {
          var startX = e.clientX
          resize[i].left = resize[i].offsetLeft
          // 鼠标拖动事件
          document.onmousemove = function(e) {
            var endX = e.clientX
            var moveLen = resize[i].left + (endX - startX) // （endx-startx）=移动的距离。resize[i].left+移动的距离=左边区域最后的宽度
            // console.log(box[i])
            var maxT = box[i].clientWidth - resize[i].offsetWidth // 容器宽度 - 左边区域的宽度 = 右边区域的宽度

            if (moveLen < 150) moveLen = 150 // 左边区域的最小宽度为150px
            if (moveLen > maxT - 500) moveLen = maxT - 500 // 右边区域最小宽度为150px

            resize[i].style.left = moveLen // 设置左侧区域的宽度

            for (let j = 0; j < left.length; j++) {
              left[j].style.width = moveLen + 'px'
              right[j].style.width = (box[i].clientWidth - moveLen - 22) + 'px'
            }
          }
          // 鼠标松开事件
          document.onmouseup = function(evt) {
            document.onmousemove = null
            document.onmouseup = null
            resize[i].releaseCapture && resize[i].releaseCapture() // 当你不在需要继续获得鼠标消息就要应该调用ReleaseCapture()释放掉
          }
          resize[i].setCapture && resize[i].setCapture() // 该函数在属于当前线程的指定窗口里设置鼠标捕获
          return false
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.fileManagement {
    .dragBox {
        display: flex;

        .left {
            width: calc(30% - 22px);
        }

        .right {
            width: 70%;

            .tableRibbon {
                display: flex;
                align-items: center;
                justify-content: space-between;

                .pathArea {
                  max-width: calc(100% - 104px);

                  .pathUrl {
                    display: inline-block;
                    font-size: 14px;
                    color: #475466;

                    span {
                        margin-left: 5px;
                        cursor: pointer;
                        &:hover {
                            color: blue;
                        }
                    }

                    i {
                        margin-right: 5px;
                    }
                  }
                }
            }
        }

        .resize {
            border-right: 2px solid #f4f4f5;
            margin: 0 10px;
            cursor:ew-resize;
        }
    }

    .contextmenu {
        margin: 0;
        background: #fff;
        z-index: 3000;
        position: fixed;
        list-style-type: none;
        padding: 5px 0;
        border-radius: 4px;
        font-size: 12px;
        font-weight: 400;
        color: #333;
        box-shadow: 2px 2px 3px 0 rgba(0, 0, 0, 0.3);
    }

    .contextmenu li {
        margin: 0;
        padding: 7px 16px;
        cursor: pointer;
    }

    .contextmenu li:hover {
        // background: rgb(3, 125, 243);
        background: #edeff5;
        // color: #fff;
    }
}
</style>
